package com.ds.esd.localproxy.handler.dsm;


import com.ds.common.JDSConstants;
import com.ds.common.JDSException;
import com.ds.common.logging.Log;
import com.ds.common.logging.LogFactory;
import com.ds.context.JDSActionContext;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.client.Project;
import com.ds.esd.custom.CustomViewFactory;
import com.ds.esd.custom.bean.ApiClassConfig;
import com.ds.esd.custom.bean.MethodConfig;
import com.ds.esd.dsm.DSMFactory;
import com.ds.esd.editor.enums.PackagePathType;
import com.ds.esd.editor.enums.PackageType;
import com.ds.esd.localproxy.handler.AbstractRADHandler;
import com.ds.esd.tool.module.EUModule;
import com.ds.esd.tool.ui.component.form.HiddenInputComponent;
import com.ds.esd.tool.ui.component.form.HiddenInputProperties;
import com.ds.server.httpproxy.core.HttpRequest;
import com.ds.server.httpproxy.core.HttpResponse;
import com.ds.server.httpproxy.core.Server;
import com.ds.web.RequestMethodBean;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;


public class DSMContextHandler extends AbstractRADHandler {
    private static final Log logger = LogFactory.getLog(JDSConstants.CONFIG_KEY, DSMContextHandler.class);
    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {
        // logger.info("request url " + request.getPath());
        boolean ruleMatches = rule.matcher(request.getPath()).matches();
        if (!ruleMatches) {
            return false;
        }
        EUModule module = null;
        String projectName = this.getProjectName(request);
        RequestMethodBean methodBean = this.getRequestMethodBean(request);
        Map<String, Object> allParamsMap = this.getAllParamMap(methodBean, request);
        try {
            Object obj = allParamsMap.get(CUSSCLASSNAME);
            if (obj != null && !obj.equals("") && !obj.equals("RAD")) {
                String currClassName = obj.toString();
                MethodConfig topMethodConfig = ESDFacrory.getESDClient().getMethodAPIBean(currClassName, projectName);
                if (topMethodConfig != null) {
                    ApiClassConfig apiConfig = DSMFactory.getInstance().getAggregationManager().getApiClassConfig(topMethodConfig.getSourceClassName(), topMethodConfig.getDomainId());
                    if (apiConfig != null) {
                        topMethodConfig = apiConfig.getMethodByName(topMethodConfig.getMethodName());
                    }
                    JDSActionContext.getActionContext().getContext().put(CustomViewFactory.TopMethodBeanKey, topMethodConfig);
                    module = ESDFacrory.getESDClient().getModule(currClassName, projectName);
                }
            }

            if (module == null && methodBean != null && projectName != null && !projectName.equals("") && !projectName.equals("RAD")) {
                allParamsMap.put("projectName", projectName);
                String path = CustomViewFactory.getInstance().formatPath(request.getPath(), projectName);
                MethodConfig methodConfig = ESDFacrory.getESDClient().getMethodAPIBean(path, projectName);
                if (methodConfig != null) {
                    ApiClassConfig apiConfig = DSMFactory.getInstance().getAggregationManager().getApiClassConfig(methodConfig.getSourceClassName(), methodConfig.getDomainId());
                    if (apiConfig != null) {
                        methodConfig = apiConfig.getMethodByName(methodConfig.getMethodName());
                    }
                }

                JDSActionContext.getActionContext().getContext().put(CustomViewFactory.TopModuleKey, module);
                if (methodConfig != null && methodConfig.isModule()) {
                    Project project = ESDFacrory.getESDClient().getProjectByName(projectName);
                    if (project != null) {
                        allParamsMap.put("projectId", project.getId());
                        PackagePathType packagePathType = PackagePathType.startPath(path);
                        if (packagePathType == null || packagePathType.getApiType().equals(PackageType.local)) {
                            module = ESDFacrory.getESDClient().getCustomModule(methodBean.getUrl(), projectName, allParamsMap);
                        } else {
                            module = ESDFacrory.getESDClient().getDSMModule(methodBean.getUrl(), allParamsMap);
                        }
                    } else {
                        logger.warn("DSM环境初始化失败，未发现可用的工程！");
                    }
                }
            }

            if (methodBean != null) {
                MethodConfig methodAPIBean = ESDFacrory.getESDClient().getMethodAPIBean(methodBean.getUrl(), projectName);
                if (methodAPIBean != null) {
                    ApiClassConfig apiConfig = DSMFactory.getInstance().getAggregationManager().getApiClassConfig(methodAPIBean.getSourceClassName(), methodAPIBean.getDomainId());
                    if (apiConfig != null) {
                        methodAPIBean = apiConfig.getMethodByName(methodAPIBean.getMethodName());
                    }
                    JDSActionContext.getActionContext().getContext().put(CustomViewFactory.MethodBeanKey, methodAPIBean);
                }

            }

            if (module != null) {
                JDSActionContext.getActionContext().getContext().put(CustomViewFactory.TopModuleKey, module);
                JDSActionContext.getActionContext().getContext().put(CustomViewFactory.CurrModuleKey, module);


                Set<Map.Entry> paramsKeys = module.getComponent().getCtxBaseComponent().getCtxMap().entrySet();
                for (Map.Entry entry : paramsKeys) {
                    if (entry.getValue() != null) {
                        HiddenInputComponent hiddenInputComponent = (HiddenInputComponent) entry.getValue();
                        HiddenInputProperties properties = (HiddenInputProperties) hiddenInputComponent.getProperties();
                        JDSActionContext.getActionContext().getPagectx().put(properties.getName(), properties.getValue());
                    }
                }
            }
        } catch (JDSException e) {
            response.sendError(500, e.getMessage());
            e.printStackTrace();
        }
        return false;
    }


}
